package genesis.familytree.server.common.code.builder;


import genesis.familytree.server.common.code.*;
import genesis.familytree.server.common.exception.ExpressionException;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;

/**
 *
 */
public class ScriptExprBuilder extends AbstractDataTypeBuilder implements DataTypeBuilder, DataNameBuilder {

    @Override
    public String build(String name, String format, Params params) throws ExpressionException {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");

            if (engine == null) {
                throw new UnsupportedOperationException("not found JavaScript engine!");
            }

            Bindings bindings = new SimpleBindings(params);

            Object obj = engine.eval(format, bindings);
            return obj.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Attribute build(Expression expr, int startIndex, int endIndex, String expression) {
        int index = expression.indexOf(":");
        if (index == -1) {
            return null;
        }

        String name = expression.substring(0, index);
        if (!"script".equals(name)) {
            return null;
        }
        String format = expression.substring(index + 1);
        return new Attribute(expr, startIndex, endIndex, "script", "script", format);
    }

}
